package com.haibei;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.app.Application;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.common.uitl.LogUtil;
import com.common.uitl.StringUtils;
import com.haibei.adapter.bean.ArticleCategory;
import com.haibei.adapter.bean.City;
import com.haibei.adapter.bean.User;
import com.haibei.cache.list.fanou.LazyImageLoader;

public class App extends Application {

	public static final String tag = "haibei";

	private HttpClient httpClient;
	public boolean isLogin = false;
	public User user;
	public static App app;
	public LocationClient mLocationClient = null;
	public MyLocationListenner myListener = new MyLocationListenner();
	private ArrayList<ArticleCategory> categoryItem;
	public static LazyImageLoader mImageLoader;
	public static ArrayList<City> mArrayListFirstLevelCity = new ArrayList<City>();// 省份，包含城市
	public static HashMap<String, City> cityMap = new HashMap<String, City>();
	public static City currentCity;

	@Override
	public void onCreate() {
		super.onCreate();
		httpClient = this.createHttpClient();
		app = this;
		mImageLoader = new LazyImageLoader();
		mLocationClient = new LocationClient(this);
		mLocationClient.registerLocationListener(myListener);
		JPushInterface.setDebugMode(true); // 设置开启日志,发布时请关闭日志
		JPushInterface.init(this); // 初始化 JPush

	}

	public static App getApp() {
		return app;
	}

	public static boolean isLogin() {
		return (null == getApp().getUser() ? false : true);
	}

	public static void logout() {
		App systemApp = App.getApp();
		systemApp.setUser(null);
	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
		this.shutdownHttpClient();
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
		this.shutdownHttpClient();
	}

	// 创建HttpClient实例
	private HttpClient createHttpClient() {
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
		HttpProtocolParams.setUseExpectContinue(params, true);
		HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
		HttpConnectionParams.setSoTimeout(params, 20 * 1000);
		HttpConnectionParams.setSocketBufferSize(params, 8192);
		SchemeRegistry schReg = new SchemeRegistry();
		schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
		ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, schReg);
		return new DefaultHttpClient(connMgr, params);
	}

	public void saveUser() {

	}

	public void loadUser() {

	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
		if(null!=user){
			Set<String> tagSet = new HashSet<String>();
			tagSet.add(user.getUid());
			try {
				JPushInterface.setTags(this, tagSet, new TagAliasCallback() {
					@Override
					public void gotResult(int arg0, String arg1, Set<String> arg2) {
						LogUtil.e(App.tag, "arg0:" + arg0 + " arg1:" + arg1 + " arg2:" + arg2.toString());
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	// 关闭连接管理器并释放资源
	private void shutdownHttpClient() {
		if (httpClient != null && httpClient.getConnectionManager() != null) {
			httpClient.getConnectionManager().shutdown();
		}
	}

	// 对外提供HttpClient实例
	public HttpClient getHttpClient() {
		return httpClient;
	}

	public ArrayList<ArticleCategory> getCategoryItem() {
		return categoryItem;
	}

	public void setCategoryItem(ArrayList<ArticleCategory> categoryItem) {
		this.categoryItem = categoryItem;
		for (int i = 0, isize = categoryItem.size(); i < isize; i++) {
			ArticleCategory category = categoryItem.get(i);
			LogUtil.i(App.tag, category.getName() + " id :" + category.getId());
		}
	}

	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			StringBuffer sb = new StringBuffer(256);
			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				sb.append("\n省：");
				sb.append(location.getProvince());
				sb.append("\n市：");
				sb.append(location.getCity());
				sb.append("\n区/县：");
				sb.append(location.getDistrict());
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
			}
			String city = location.getCity();
			if (!StringUtils.isEmpty(city)) {
				currentCity = cityMap.get(city.substring(0, city.length() - 1));
				if (null == currentCity) {
					currentCity = cityMap.get(city.substring(0, city.length()));
				}
				if (null != currentCity && null != mLocationClient) {
					mLocationClient.stop();
					LogUtil.i(App.tag, "定位到:" + currentCity.getName() + " 停止定位！");
				}
			}
			sb.append(location.isCellChangeFlag());
			LogUtil.i(App.tag, "定位成功:" + "city id:" + (null != currentCity ? currentCity.getId() : ""));
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}
}
